package org.jerrymouse.jsa4j.search.lucene;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.jerrymouse.jsa4j.search.Searcher;
import org.jerrymouse.jsa4j.search.SearcherManager;

public class LuceneSearcherManager implements SearcherManager {
	private Analyzer analyzer;
	private Directory directory;

	private Analyzer getAnalyzer() {
		if (analyzer == null)
			analyzer = new SmartChineseAnalyzer(Version.LUCENE_30);
		return analyzer;
	}

	private Directory getDirectory() {
		if (directory == null) {
			try {
				directory = FSDirectory.open(new File(getBasePath()));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return directory;
	}

	@Override
	public Searcher getSearcher() {
		LuceneSearcher index = new LuceneSearcher();
		index.setAnalyzer(getAnalyzer());
		index.setDirectory(getDirectory());
		return index;
	}

	@Override
	public void setProperties(Map<String, String> properties) {
		this.properties = properties;
	}

	private Map<String, String> properties = new HashMap<String, String>();

	private String getBasePath() {
		if (properties == null) {
			properties = new HashMap<String, String>();
		}
		if (properties.get("basePath") == null) {
			String basePath = System.getProperty("user.home")
					+ "/.jsa4j/search/";
			properties.put("basePath", basePath);
		}
		return properties.get("basePath");
	}
}
